//
//  LearnCourse.swift
//  ddx0513
//
//  Created by jiang yongbin on 15/5/31.
//  Copyright (c) 2015年 jiang yongbin. All rights reserved.
//

import UIKit

class LearnCourse: UITableViewController {

    
    //var learnArr:NSMutableArray = []
    var lessonId:NSMutableArray = []
    var lessonName:NSMutableArray = []
    var lessonImg:NSMutableArray = []
    var learnProgress:NSMutableArray = []
    var sectionNum:NSMutableArray = []
    var learncourseitem:LearnCourseItem! = nil
    var totalPage = 0
    var pageSize = 3
    var pageNum = 1
    var thisPage = 0
    var searchTime: Int64?
    var totalCount = 0
    
   // @IBOutlet weak var learnCourseName: UILabel!

    func datainit()
    {
        thisPage = 0
        lessonId.removeAllObjects()
        lessonName.removeAllObjects()
        sectionNum.removeAllObjects()
        lessonImg.removeAllObjects()
        learnProgress.removeAllObjects()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.tableFooterView = UIView(frame: CGRectZero)
        self.tableView.header = MJRefreshNormalHeader(refreshingBlock: { () -> Void in
            self.datainit()
            self.learn(1)
        })
        self.tableView.header.beginRefreshing()

    
    }
    func learn(pageNum: Int) {
        
        var a: [String: AnyObject]?
        var userid:Int = DBUtils.mem.userId
        var token:String = DBUtils.mem.token
        a = ["userid":userid,"token":token,"pn":pageNum,"ps":pageSize]
        if (pageNum > 1) {
            a?.updateValue(NSNumber(longLong: self.searchTime!), forKey: "searchtime")
        }
        NetUtils.netRequest(Method.GET, URLString: NetUtils.getURLStudying() , parameters: a, responseHandler: nil, netErrorHandler: nil, successHandler: learnlist, interErrorHandler: nil, jsonErrorHandler: nil)
    }
    func learnlist(json: JSON) {
        
        totalCount = json["totalcount"].int!
        let listNum = json["list"].count
        for (var i = 0;i < listNum; i++ )
        {
            lessonId.addObject(json["list"][i]["lessonid"].int!)
            lessonName.addObject(json["list"][i]["lessonname"].string!)
            //sectionNum.addObject(json["list"][i]["sectionnum"].int!)
            lessonImg.addObject(json["list"][i]["imgurl"].string!)
            sectionNum.addObject(json["list"][i]["sectionnum"].int!)
            learnProgress.addObject(json["list"][i]["progress"].int!)
            

        }
        thisPage++
        self.tableView.reloadData()
        
        if (self.thisPage == 1) {
            self.tableView.header.endRefreshing()
            self.searchTime = json["searchtime"].int64!
            self.totalPage = Int(ceil(Double(totalCount) / Double(pageSize)))
            
            self.tableView.footer = MJRefreshAutoNormalFooter(refreshingBlock: { () -> Void in
                self.learn(self.thisPage+1)
            })
            
            if (self.totalPage == self.thisPage) {
                self.tableView.footer.noticeNoMoreData()
            }
        }
        
        if (self.totalPage > self.thisPage) {
            self.tableView.footer.endRefreshing()
        } else {
            self.tableView.footer.noticeNoMoreData()
        }

        
        


    
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return lessonId.count
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
 
        var tableCell :LearnCourseItem = tableView.dequeueReusableCellWithIdentifier("LearnCourseItem") as! LearnCourseItem
        
        var s = lessonName.objectAtIndex(indexPath.row) as? String
        tableCell.learnCourseName.text = s;
        //tableCell.lessonProgress.progressImage = UIImage(named: "进度条.png")
        //tableCell.lessonProgress.trackImage = UIImage(named: "进度条.png")
        //img3b.image = img3b2!.imageWithGradientTintColor(UIColor(red: 241/255, green: 215/255, blue: 79/255, alpha: 1.0))
        var a = learnProgress.objectAtIndex(indexPath.row) as! Float
        var b = sectionNum.objectAtIndex(indexPath.row) as! Float
        var c = a / b

        var transform:CGAffineTransform = CGAffineTransformMakeScale(1.0, 3.0)
       tableCell.lessonProgress.transform = transform
       
       tableCell.lessonProgress.layer.masksToBounds.boolValue
       tableCell.lessonProgress.layer.cornerRadius = 10
       tableCell.lessonProgress.clipsToBounds = true
       //tableCell.lessonProgress.maskView?.bounds
        
      //pro1.progressTintColor=[UIColor redColor];

        
        tableCell.lessonProgress.setProgress(c, animated: false)
        var url:String = lessonImg.objectAtIndex(indexPath.row) as! String
        DBUtils.getImageFromFile(url, successHandler: { (imgUrl, img) -> Void in
            if (url == imgUrl) {
                tableCell.lessonImg.image = img
            }
        })
        
        tableCell.accessoryType = UITableViewCellAccessoryType.None

        //////////////////
     

        return tableCell as UITableViewCell
    }

    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {

        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        var allcoursedetail = UIStoryboard(name: "AllCourse", bundle: nil).instantiateViewControllerWithIdentifier("AllCourseDetail") as! AllCourseDetail
   
        rootController.navigationController?.pushViewController(allcoursedetail, animated: true)
        var lessonid = lessonId.objectAtIndex(indexPath.row) as! Int

        allcoursedetail.lessonId = lessonid
        
        var lessonname = lessonName.objectAtIndex(indexPath.row) as? String
        allcoursedetail.lessonName = lessonname!
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

}
